const moment = require("moment");
const McMeetingUserRelation = require('./db/mc_meeting_user_relation')
const McMeeting = require('./db/mc_meeting')
const path = require('path');
const clouddb = require('@hw-agconnect/database-server/dist/index.js')
import { AGCClient, CredentialParser } from '@agconnect/common-server';

// 加载凭证文件
let client_name = "./db/agc-apiclient-mlc.json";
let client_path = path.join(__dirname, client_name);
let credential = CredentialParser.toCredential(client_path);
AGCClient.initialize(credential, "clientDW");
const agcClient = AGCClient.getInstance("clientDW");
clouddb.AGConnectCloudDB.initialize(agcClient);
const agconnectCloudDB = clouddb.AGConnectCloudDB.getInstance(agcClient);

//云数据库区块
const zoneName = 'mlc01';
const cloudDBZoneConfig = new clouddb.CloudDBZoneConfig(zoneName);
const mCloudDBZone = agconnectCloudDB.openCloudDBZone(cloudDBZoneConfig);

let myHandler = async function (event, context, callback, logger) {
  const { userId, days = 7 } = event.body ? JSON.parse(event.body) : event

  const querys = []
  for (let i = 0; i < days; i++) {
    const cloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeetingUserRelation.mc_meeting_user_relation)
    const createCloudDBZoneQuery = clouddb.CloudDBZoneQuery.where(McMeeting.mc_meeting)
    const startDate = moment().utcOffset(0).startOf('day').add(-i, 'd').toDate()
    const endDate = moment().utcOffset(0).startOf('day').add(-i + 1, 'd').toDate()

    const query = cloudDBZoneQuery.equalTo("userId", userId)
      .lessThanOrEqualTo("startTime", endDate)
      .greaterThanOrEqualTo("startTime", startDate)

    const createQuery = createCloudDBZoneQuery.equalTo("createBy", userId)
      .lessThanOrEqualTo("startTime", endDate)
      .greaterThanOrEqualTo("startTime", startDate)
    const num1 = mCloudDBZone.executeCountQuery(query, "id")
    const num2 = mCloudDBZone.executeCountQuery(createQuery, "id")
    querys.push(new Promise(async (resolve) => {
      const [numRes1, numRes2] = await Promise.all([num1, num2])
      resolve({
        name: moment(startDate).format('MM/DD'),
        value: Number(numRes1) + Number(numRes2)
      })
    }));
  }

  const res = await Promise.all(querys)

  res.sort(function (a, b) {
    // 将name转换为日期进行比较，确保正确的日期顺序
    var dateA = new Date('20/' + a.name).getTime();
    var dateB = new Date('20/' + b.name).getTime();
    return dateA - dateB;
  });
  // const res = await Promise.all(querys)

  callback({
    code: 200,
    desc: "成功",
    data: res.reverse()
  });
};

export { myHandler };